#!/bin/bash

# 加载配置
source "./config.env"

# 错误退出函数
fail() {
    echo "❌ Error: $@" >&2
    exit 1
}

# 检查关键文件存在
check_for_file() {
    [ -e "$1" ] || fail "缺失文件: $1"
}

# 1. 检查 steamcmd 目录和启动文件
cd "$steamcmd_dir" || fail "目录不存在: $steamcmd_dir"
check_for_file "steamcmd.sh"

# 2. 检查存档和配置
check_for_file "$dontstarve_dir/$cluster_name/cluster.ini"
check_for_file "$dontstarve_dir/$cluster_name/cluster_token.txt"
check_for_file "$dontstarve_dir/$cluster_name/Master/server.ini"
check_for_file "$dontstarve_dir/$cluster_name/Caves/server.ini"

# 3. 切换到安装目录
cd "$install_dir/bin64" || fail "进入 $install_dir/bin64 失败"

# 4. 构造运行参数
run_shared=(./dontstarve_dedicated_server_nullrenderer_x64)
run_shared+=(-console)
run_shared+=(-cluster "$cluster_name")
run_shared+=(-monitor_parent_process $$)
run_shared+=(-shard)

# 5. 启动两个 shard
mkdir -p logs
echo "🚀 启动 Caves..."
"${run_shared[@]}" Caves  > "$log_dir/caves.log" 2>&1 &

echo "🚀 启动 Master..."
"${run_shared[@]}" Master > "$log_dir/master.log" 2>&1

echo "✅ 饥荒服务器已启动（集群名：$cluster_name）"